package com.nosnow.edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nosnow.edu.entity.EduSubject;
import com.nosnow.edu.entity.excel.SubjectData;
import com.nosnow.edu.entity.subject.OneSubject;
import com.nosnow.edu.entity.subject.TwoSubject;
import com.nosnow.edu.listener.SubjectExcelListener;
import com.nosnow.edu.mapper.EduSubjectMapper;
import com.nosnow.edu.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author bingheng
 * @since 2020-04-04
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void saveSubject(MultipartFile file, EduSubjectService eduSubjectService) throws Exception{

        // 1. 获取文件输入流
        InputStream inputStream = file.getInputStream();

        // 2. 调用方法进行读取excel数据
        EasyExcel.read(inputStream, SubjectData.class, new SubjectExcelListener(eduSubjectService)).sheet().doRead();
    }

    @Override
    public List<OneSubject> getAllOneTwoSubject() {

        // 1. 查询所有的一级分类
        QueryWrapper<EduSubject> OneWrapper = new QueryWrapper<>();
        OneWrapper.eq("parent_id", "0");
        List<EduSubject> oneList = baseMapper.selectList(OneWrapper);

        // 2. 查询所有的二级分类
        QueryWrapper<EduSubject> twoWrapper = new QueryWrapper<>();
        twoWrapper.ne("parent_id", "0");
        List<EduSubject> twoList = baseMapper.selectList(twoWrapper);

        // 3. 创建最终的List集合
        List<OneSubject> resultList = new ArrayList<>();

        // 4. 将oneList 中的数据放入到resultList中去
        if(oneList != null && !oneList.isEmpty()) {
            oneList.forEach(o -> {
                OneSubject oneSubject = new OneSubject();
                BeanUtils.copyProperties(o, oneSubject);
                resultList.add(oneSubject);

                // 4.1 将二级分类放入到对用的一级分类中
                List<TwoSubject> twoSubjects = new ArrayList<>();
                if(twoList != null && !twoList.isEmpty()) {
                    twoList.forEach(t -> {
                        if(t.getParentId().equals(o.getId())) {
                            TwoSubject twoSubject = new TwoSubject();
                            BeanUtils.copyProperties(t, twoSubject);
                            twoSubjects.add(twoSubject);
                        }
                    });
                }
                oneSubject.setChildren(twoSubjects);
            });
        }
        return resultList;
    }
}
